package com.sskj.market.ui.activity;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.MD5Util;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.market.R;
import com.sskj.market.R2;
import com.sskj.market.bean.OrderListBean;
import com.sskj.market.component.DaggerUserDataComponent;
import com.sskj.market.http.HttpConfig;
import com.sskj.market.presenter.OrderItemPresenter;
import com.sskj.market.util.GlideUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * 订单列表fragment
 *
 * @author budou
 */
public class OrderItemFragment extends BaseFragment<OrderItemPresenter> {


    @BindView(R2.id.recycle_order_item)
    RecyclerView recycleOrderItem;
    @BindView(R2.id.refresh_order_item)
    CoolRefreshView refreshOrderItem;

    @Inject
    UserViewModel userViewModel;
    UserData userData;
    List<OrderListBean> data = new ArrayList<>();

    /**
     * 默认展示全部页面
     */
    private int type = 0;
    private MVCCoolHelper<List<OrderListBean>> mvcHelper;

    @Override
    protected int getLayoutId() {
        return R.layout.market_fragment_order_item;
    }

    @Override
    protected OrderItemPresenter getPresenter() {
        return new OrderItemPresenter();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
    }


    @Override
    protected void initView() {
        super.initView();
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });

        Bundle bundle = getArguments();
        assert bundle != null;
        type = bundle.getInt("orderType");

    }

    @Override
    protected void initData() {
        super.initData();
        recycleOrderItem.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleOrderItem.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 10))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );

        @SuppressWarnings("unchecked")
        SlimAdapter<OrderListBean> slimAdapter = SlimAdapter.create().
                register(R.layout.market_item_order_list, new SlimInjector<OrderListBean>() {
                    @Override
                    public void onInject(OrderListBean o, IViewInjector iViewInjector, List list) {
                        String allPrice = String.valueOf(Double.parseDouble(o.getTotal_price()) + Double.parseDouble(o.getShipping_money()));
                        GlideUtils.Show( o.getProduct().getPics().get(0), (ImageView) iViewInjector.findViewById(R.id.iv_item_head_order_list_market));
                        iViewInjector.text(R.id.tv_item_id_order_list_market, App.INSTANCE.getString(R.string.market_orderItemFragment1) + o.getSn())
                                .text(R.id.tv_item_name_order_list_market, o.getProduct().getName())
                                .text(R.id.tv_item_remark_order_list_market, App.INSTANCE.getString(R.string.market_orderItemFragment2) + o.getRemark())
                                .text(R.id.tv_item_price_order_list_market, NumberUtil.keep(allPrice,2) + "LAC");
                        switch (o.getStatus()) {
                            case 1:
                                iViewInjector.text(R.id.tv_item_type_order_list_market, App.INSTANCE.getString(R.string.market_orderListActivity2))
                                        .text(R.id.btn_item_right_order_list, App.INSTANCE.getString(R.string.market_orderItemFragment4))
                                        .text(R.id.btn_item_left_order_list, App.INSTANCE.getString(R.string.market_orderItemFragment5))
                                        .visible(R.id.view_item_bottom)
                                        .visible(R.id.btn_item_left_order_list)
                                        .visible(R.id.btn_item_right_order_list)
                                        .clicked(R.id.btn_item_left_order_list,
                                                view -> {
                                                    if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                                                        return;
                                                    }
                                                    mPresenter.cancelOrder(o.getId() + "");
                                                }

                                        ).
                                        clicked(R.id.btn_item_right_order_list,
                                                view -> {
                                                    if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                                                        return;
                                                    }
                                                    showPayDialog(o.getSn(), allPrice);
                                                });
                                break;
                            case 2:
                                iViewInjector.text(R.id.tv_item_type_order_list_market, App.INSTANCE.getString(R.string.market_orderListActivity3))
                                        .gone(R.id.view_item_bottom)
                                        .gone(R.id.btn_item_left_order_list)
                                        .gone(R.id.btn_item_right_order_list);
                                break;
                            case 3:
                                iViewInjector.text(R.id.tv_item_type_order_list_market, App.INSTANCE.getString(R.string.market_orderListActivity4))
                                        .text(R.id.btn_item_right_order_list, App.INSTANCE.getString(R.string.market_orderItemFragment8))
                                        .visible(R.id.view_item_bottom)
                                        .gone(R.id.btn_item_left_order_list)
                                        .visible(R.id.btn_item_right_order_list)
                                        .clicked(R.id.btn_item_right_order_list,
                                                view -> {
                                                    if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                                                        return;
                                                    }
                                                    mPresenter.ensureOrder(o.getId() + "");
                                                }
                                        );
                                break;
                            case 4:
                                iViewInjector.text(R.id.tv_item_type_order_list_market, App.INSTANCE.getString(R.string.market_orderListActivity5))
                                        .gone(R.id.view_item_bottom)
                                        .gone(R.id.btn_item_left_order_list)
                                        .gone(R.id.btn_item_right_order_list);

                                break;
                            case 0:
                                iViewInjector.text(R.id.tv_item_type_order_list_market, App.INSTANCE.getString(R.string.market_orderItemFragment10))
                                        .text(R.id.btn_item_right_order_list, App.INSTANCE.getString(R.string.market_orderItemFragment11))
                                        .visible(R.id.view_item_bottom)
                                        .gone(R.id.btn_item_left_order_list)
                                        .visible(R.id.btn_item_right_order_list)
                                        .clicked(R.id.btn_item_right_order_list,
                                                view -> {
                                                    if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                                                        return;
                                                    }
                                                    mPresenter.deleteOrder(o.getId() + "");
                                                }
                                        );
                                break;
                            default:
                                break;
                        }
                    }
                }).attachTo(recycleOrderItem).updateData(data);

        //
        ModelRx2DataSource<OrderListBean> dataSource =
                new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<OrderListBean>)
                        page -> {
                            return mPresenter.getAllList(page + "", type);
                        }
                );
        mvcHelper = new MVCCoolHelper<>(refreshOrderItem);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
        ItemClickSupport.addTo(recycleOrderItem)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt("orderId", data.get(position).getId());
                    Intent intent = new Intent(getActivity(), OrderDetailsActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                });

    }


    /**
     * 取消成功
     */
    public void cancelSuccess() {
        mvcHelper.refresh();
        ToastUtil.showShort(App.INSTANCE.getString(R.string.market_cancel_success));
    }

    /**
     * 删除成功
     */
    public void deleteSuccess() {
        mvcHelper.refresh();
        ToastUtil.showShort(App.INSTANCE.getString(R.string.market_delete_success));
    }

    /**
     * 确认收货成功
     */
    public void ensureSuccess() {
        mvcHelper.refresh();
        ToastUtil.showShort(App.INSTANCE.getString(R.string.market_ensure_success));
    }

    /**
     * 支付成功
     */
    public void paySuccess() {
        mvcHelper.refresh();
        ToastUtil.showShort(App.INSTANCE.getString(R.string.market_pay_success));
    }

    @SuppressLint("SetTextI18n")
    private void showPayDialog(String sn, String allPrice) {
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(getActivity())
                .inflate(R.layout.market_dialog_pay, null);
        Dialog dialog = new Dialog(Objects.requireNonNull(getActivity()), R.style.market_bottom_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Button btnEnsure = view.findViewById(R.id.btn_pay_ensure_dialog);
        TextView tvPrice = view.findViewById(R.id.tv_pay_price_dialog);
        EditText etPay = view.findViewById(R.id.et_pay_input_dialog);
        tvPrice.setText(App.INSTANCE.getString(R.string.market_orderItemFragment12) + NumberUtil.keep(allPrice,2) + "LAC");

        ClickUtil.click(btnEnsure, () -> {
            if (TextUtils.isEmpty(etPay.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.market_orderItemFragment13));
                return;
            }
            mPresenter.payOrder(sn, MD5Util.getMd5Value(etPay.getText().toString()));
            dialog.dismiss();
        });
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        view.setLayoutParams(layoutParams);
        Objects.requireNonNull(dialog.getWindow()).setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.market_pop_show_style);
        dialog.show();

    }

    @Override
    public void onStart() {
        super.onStart();
        mvcHelper.refresh();
    }
}
